package com.jzrh.flashbee.controller;

import com.jzrh.flashbee.common.core.base.BaseController;
import com.jzrh.flashbee.entity.dto.UrlDTO;
import com.jzrh.flashbee.entity.vo.UrlVO;
import com.jzrh.flashbee.service.IFlashbeeUrlService;
import com.jzrh.flashbee.common.utils.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author: Administrator-CCENOTE
 * @since: 2023/11/22 18:43
 * @description: 短网址生成控制器
 */
@RestController
@RequestMapping("/")
public class UrlController extends BaseController {
    @Resource
    private IFlashbeeUrlService flashbeeUrlService;
    /**
     * 生成短网址
     */
    @GetMapping("/generate")
    public Result<UrlVO> generate(UrlDTO urlDTO, HttpServletRequest request){
        return Result.success("生成成功",flashbeeUrlService.generateUrl(urlDTO,request));
    }

    /**
     * 生成演示网址
     */
    @GetMapping("/generateDemo")
    public Result<UrlVO> generateDemo(UrlDTO urlDTO,HttpServletRequest request){
        urlDTO.setExpiration(1);
        return Result.success("生成成功",flashbeeUrlService.generateUrl(urlDTO,request));
    }

    /**
     * 跳转源地址
     */
    @GetMapping("/{shortUrl}")
    public void toOriginUrl(HttpServletResponse response,@PathVariable String shortUrl) throws IOException {
        if(StringUtils.isNotBlank(shortUrl)){
            String originUrl = flashbeeUrlService.getOriginUrl(shortUrl);
            response.sendRedirect(originUrl);
            return;
        }
        response.getWriter().write("短网址以失效");
    }
}
